//
//  MyInformationViewController.m
//  LovingPartyBuilding
//
//  Created by 刘应平 on 17/5/2.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "MyInformationViewController.h"
#import "MyInformationTableViewCell.h"
#import "MyInformationHeadTableViewCell.h"
#import "ZJPhotographSelector.h"
#import "AlertWindow.h"
#import "MyInforHeadModel.h"
#import "MyInforNormalModel.h"
#import "NetWorkUpLoadModel.h"
/**  修改姓名  */
#import "MyInforChangeNameViewController.h"
/**  修改性别  */
#import "MyInforChangeSexViewController.h"
/**  修改手机号  */
#import "MyInforChangePhoneViewController.h"
/**  查看二维码  */
#import "MyInforLookerWeiMaViewController.h"
#import "ZJReportDetailViewController.h"
#import "LPGainPath.h"
#import "LZActionSheetView.h"
#import "ZJBOorganizationModel.h"
@interface MyInformationViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
/**  table  */
@property (strong, nonatomic) UITableView  *tableView;
/**  titile  */
@property (strong, nonatomic) NSMutableArray  *titlesArray;
/**  获取位置  */
@property (strong, nonatomic) NSIndexPath  *indexPATH;
/**  iamgepic  */
@property (strong, nonatomic) UIImagePickerController  *imagePickerController;

@end

@implementation MyInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"我的信息";
    [self getDataSource];
    [self layoutUI];
    
    /**  注册手机号返回通知  */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneNumberNoti:) name:@"sendPhoneNumber" object:nil];
}


#pragma mark - 数据
- (void)getDataSource{
    ZJAccountInfo *userInfor = [ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT;
    NSString *sex;
    if ([userInfor.SEX isEqualToString:@"0"]) {
        sex = @"未设置";
    }else if ([userInfor.SEX isEqualToString:@"1"]){
        sex = @"男";
    }else{
        sex = @"女";
    }
    NSArray *arrray = @[@{@"head": ZJUSERINFORMODEL.ORG_ACCOUNT.PHOTO_URL},
                         @{@"title": @"姓名", @"erImage": @"",@"content": userInfor.USER_NAME},
                         @{@"title": @"手机号", @"erImage": @"",@"content": userInfor.MOBILE},
                         @{@"title": @"二维码", @"erImage": @"partyhelper_erweima",@"content": @""},
                         @{@"title": @"性别", @"erImage": @"",@"content": sex}
//                         @{@"title": @"积分", @"erImage": @"",@"content": @""},
//                        @{@"title": @"个人需求", @"erImage": @"",@"content": @""},
//                        @{@"title": @"个人服务", @"erImage": @"",@"content": @""}
                        ];
    
    for (int i = 0; i < arrray.count; i ++) {
        if (i == 0) {
            MyInforHeadModel *model = [MyInforHeadModel yy_modelWithDictionary:arrray[i]];
            [self.titlesArray addObject:model];
        }else{
            MyInforNormalModel *model = [MyInforNormalModel yy_modelWithDictionary:arrray[i]];
            [self.titlesArray addObject:model];

        }
    }
    
}


#pragma mark - 界面
- (void)layoutUI{
    [self.view addSubview:self.tableView];
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], 12 * [UIScreen zj_screenHScale])];
    head.backgroundColor = [UIColor themeGrayColor];
    self.tableView.tableHeaderView = head;
    
}

- (void)action_leftButton:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 私有方法
/**  通知回调  */
- (void)phoneNumberNoti:(NSNotification *)noti{
    MyInforNormalModel *model = self.titlesArray[2];
    model.content = noti.userInfo[@"phone"];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:self.indexPATH, nil] withRowAnimation:UITableViewRowAnimationNone];
}

//相册
- (void)accessPhotoALbm{
    //1、获取支持的媒体格式
    NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    //2、判断是否支持的sourceType
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        //3、设置sourceType
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //4、设置媒体格式
        _imagePickerController.mediaTypes = @[mediaTypes.firstObject];
        //5、设置是否允许编辑  如果该属性为NO 就不会进入到照片的编辑界面
//        _imagePickerController.allowsEditing = YES;
        //6、推送
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
        
    }else{
        
        [YJProgressHUD showMsgWithoutView:@"设备不支持访问相册"];
    }
}

- (void)visitCamer{
    /**  访问相机  */
    // 1.获取支持的媒体格式,访问本地相册使用
    NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    //2.判断是否支持需要设置的sourceType
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        // 3.设置SourceType
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        // 4.设置媒体格式
        _imagePickerController.mediaTypes = @[mediaTypes.firstObject];
        // 5.设置相机模式
        _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        // 6.设置摄像头(前置和后置)
        _imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        // 7.设置闪光模式
        _imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        //8.推送
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
        
    }else{
        [YJProgressHUD showMsgWithoutView:@"设备不支持访问拍照"];
    }
}


#pragma mark -上传图片
- (void)upLoadImage:(UIImage *)image imageName:(NSString *)name{
    
    NetWorkUpLoadModel *loadModel = [NetWorkUpLoadModel new];
    NetWorkUploadFileModel *filrModel = [NetWorkUploadFileModel new];
    UIImage *newImage = [UIImage scaleImage:image toScale:0.5];
    //UIImage转换为NSData
    NSData *imageData = UIImagePNGRepresentation(newImage);
    filrModel.FILE_PATH = imageData;
    filrModel.FILE_NAME = name;
    filrModel.FILE_INDEX = @"0";
    filrModel.NAME = @"PHOTO";
    loadModel.UPLOAD_FILES = @[filrModel];
    loadModel.ACCOUNT_ID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    [YJProgressHUD showMessage:@"更新中..." duration:10 view:self.view];
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager uploadingWithXMLString:[NetWorkingURL getUpdateUser] Parameter:loadModel Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"更新成功" inview:weakSelf.view];
            MyInformationHeadTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.indexPATH];
            UIImage *imgae = newImage;
            cell.headImageView.image = imgae;
            /**  发送头像变换通知  */
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeHeaderImage" object:weakSelf userInfo:@{@"image":imgae}];
            
            /**  保存修改信息  */
            [ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.PHOTO_URL = [object objectForKey:@"PHOTO_URL"];
            
            [ZJUserInfoModel updateUserInfoToNSUserDefaults];
            
        }else{
            [YJProgressHUD showMessage:@"更新失败" inView:weakSelf.view];
        }
        
    } Fail:^(id object) {
        [YJProgressHUD showMessage:@"更新失败" inView:weakSelf.view];
    }];
    
}

#pragma mark - 协议代理
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

        NSString *dateString = [NSDate getCurrentDate];
    
        [self upLoadImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] imageName:[NSString stringWithFormat:@"%@.png",dateString]];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - /**  UITableViewDataSource,UITableViewDelegate  */
/**  返回组个数  */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
/**  返回cell个数  */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titlesArray.count;
}
/**  返回cell高度  */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 60 * [UIScreen zj_screenHScale];
    }else{
         return 50 * [UIScreen zj_screenHScale];
    }
   
}
/**  cell初始化  */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *weizhi = [NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row];
    
    if (indexPath.row == 0) {
        MyInformationHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:weizhi];
        if (!cell) {
            cell = [[MyInformationHeadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:weizhi];
        }
        cell.model = self.titlesArray[indexPath.row];
         return cell;
    }else{
        
        MyInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:weizhi];
        if (!cell) {
            cell = [[MyInformationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:weizhi];
        }
        cell.model = self.titlesArray[indexPath.row];
        cell.row = indexPath.row;
                
         return cell;
    }
   
}
/**  cell的点击事件  */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MyInforNormalModel *model = self.titlesArray[indexPath.row];
    __weak typeof(self) weakSelf = self;
    
    switch (indexPath.row) {
        case 0:{
            
            LZActionSheetView *action = [[LZActionSheetView alloc] initWithTitleView:nil optionsArr:@[@"相册", @"相机"] cancelTitle:@"取消" cancelBlock:^{
                
            } selectBlock:^(NSInteger index) {
                if (index == 0) {
                    [weakSelf accessPhotoALbm];
                }else{
                    [weakSelf visitCamer];
                }
            }];
            [self.view addSubview:action];
            
        } break;

        case 1:
            /**  姓名  */
        {
            MyInforChangeNameViewController *vc = [[MyInforChangeNameViewController alloc] init];
            vc.name = model.content;
            vc.block = ^(NSString *name){
                model.content = name;
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
            
        }
            break;

        case 2:
            /**  手机号  */
        {
            MyInforChangePhoneViewController *vc = [[MyInforChangePhoneViewController alloc] init];
            vc.phone = model.content;
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;

        case 3:
            /**  二维码  */
        {
            MyInforLookerWeiMaViewController *vc = [[MyInforLookerWeiMaViewController alloc] init];
            
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 4:
            /**  性别  */
        {
            MyInforChangeSexViewController *vc = [[MyInforChangeSexViewController alloc] init];
            vc.sex = model.content;
            vc.block = ^(NSString *sex){
                model.content = sex;
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;

        case 5:
            /**  个人需求  */
        {
            ZJBOorganizationModel *model = [ZJBOorganizationModel new];
            model.ID = ZJUSERINFORMODEL.DEPT_MODEL_JOB.ID;
            ZJReportDetailViewController *vc = [[ZJReportDetailViewController alloc] init];
            vc.model = model;
            vc.titleString = @"个人需求";
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;
        case 6:
            /**  个人服务  */
        {
            ZJBOorganizationModel *model = [ZJBOorganizationModel new];
            model.ID = ZJUSERINFORMODEL.DEPT_MODEL_JOB.ID;
            ZJReportDetailViewController *vc = [[ZJReportDetailViewController alloc] init];
            vc.model = model;
            vc.titleString = @"个人服务";
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;
        default:
            break;
    }
    
    self.indexPATH = indexPath;
}


#pragma mark - 懒加载
/**  初始化tableView  */
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.bounds.size.width, self.view.bounds.size.height - LP_TopHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor themeGrayColor];
        _tableView.tableFooterView = [UIView new];

      
    }
    return _tableView;
}

- (NSMutableArray *)titlesArray{
    if (!_titlesArray ) {
        _titlesArray = [NSMutableArray array];
    }
    return _titlesArray;

}


- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**  初始化图片拾取器  */
- (UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
    }
    return _imagePickerController;
}
@end
